package com.sunway.resource2es.controller;

import com.sunway.ddss.model.DynamicDatasourceEntity;
import com.sunway.ddss.service.DynamicDatasourceService;
import com.sunway.exception.built.BusinessException;
import com.sunway.resource2es.controller.dto.InitIndexDTO;
import com.sunway.resource2es.service.EsProcessServiceImpl;
import com.sunway.result.response.ResultVO;
import com.sunway.utils.time.TimeUtil;
import com.sunway.utils.time.enums.TimeFormatEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * ES检索
 *
 * @author lxw
 * @date 2023/12/4 13:19
 */
@Tag(name = "ES索引处理")
@Slf4j
@RestController
@RequestMapping("esProcess")
public class EsProcessController {


    private final EsProcessServiceImpl esProcessService;
    public final DynamicDatasourceService dynamicDatasourceService;

    public EsProcessController(EsProcessServiceImpl esProcessService, DynamicDatasourceService dynamicDatasourceService) {
        this.esProcessService = esProcessService;
        this.dynamicDatasourceService = dynamicDatasourceService;
    }


    @GetMapping(value = "/createEsIndex")
    @Operation(summary = "创建索引")
    @Parameters({
            @Parameter(name = "dbName", description = "数据源名称", required = true),
            @Parameter(name = "tableName", description = "数据源标中名称", required = true)
    })
    public ResultVO<List<String>> createEsIndex(@RequestParam("dbName") String dbName, @RequestParam("tableName") String tableName) {
        DynamicDatasourceEntity dyDatasourceEntity = dynamicDatasourceService.findDyDatasourceEntity(dbName);
        if (dyDatasourceEntity == null) {
            throw new BusinessException("数据源不存在");
        }
        String thisNow = TimeUtil.thisNow(TimeFormatEnum.NORM_FORMAT_DATETIME_YEAR);
        List<String> strings = esProcessService.initEsData(dbName, tableName, "has_detail=1",
                tableName + ".json", "", tableName + "_" + thisNow, tableName);
        return ResultVO.success(strings);
    }


    @Operation(summary = "输入加入到ES")
    @PostMapping("createIndex")
    public ResultVO<String> createIndex(@RequestBody InitIndexDTO indexDTO) {
        indexDTO.verifyMapping();
        indexDTO.indexNameExit();
        esProcessService.initEsData(indexDTO.getDbName(), indexDTO.getTableName(), indexDTO.getCondition()
                , indexDTO.getMappingFileName(), indexDTO.getMappingStr(), indexDTO.getIndexName(), indexDTO.getIndexAlias()
        );
        return ResultVO.success();
    }

}
